<script>
import { getCurrentInstance, reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import ProButton from '@/components/common/proButton.vue'
import UploadPicture from '@/components/common/uploadPicture.vue'
import { useStore } from 'vuex'

export default {
  components: {
    UploadPicture, ProButton
  },
  setup (props, context) {
    const globalProperties = getCurrentInstance().appContext.config.globalProperties
    const $common = globalProperties.$common
    const $http = globalProperties.$http
    const $constant = globalProperties.$constant
    const $router = useRouter()
    const $store = useStore()

    const data = reactive({
      currentUser: $store.state.currentUser,
      username: '',
      account: '',
      password: '',
      phoneNumber: '',
      email: '',
      avatar: '',
      showDialog: false,
      code: '',
      dialogTitle: '',
      codeString: '验证码',
      passwordFlag: 1,
      intervalCode: null
    })

    // 切换登录
    function signIn () {
      document.querySelector('#loginAndRegist').classList.remove('right-panel-active')
    }
    // 登录
    function login () {
      if ($common.isEmpty(data.account) || $common.isEmpty(data.password)) {
        ElMessage({
          message: '请输入账号或密码！',
          type: 'error'
        })
        return
      }

      const user = {
        account: data.account.trim(),
        password: $common.encrypt(data.password.trim())
      }

      $http.post($constant.baseURL + '/user/login', user, false, false)
        .then((res) => {
          if (!$common.isEmpty(res.data)) {
            $store.commit('loadCurrentUser', res.data)
            localStorage.setItem('userToken', res.data.accessToken)
            data.account = ''
            data.password = ''
            $router.push({ path: '/chat' })
          }
        })
        .catch((error) => {
          ElMessage({
            message: error.message,
            type: 'error'
          })
        })
    }
    // 切换注册
    function signUp () {
      document.querySelector('#loginAndRegist').classList.add('right-panel-active')
    }
    // 注册
    function regist () {
      if ($common.isEmpty(data.username) || $common.isEmpty(data.password)) {
        ElMessage({
          message: '请输入用户名或密码！',
          type: 'error'
        })
        return
      }

      if (data.dialogTitle === '邮箱验证码' && $common.isEmpty(this.email)) {
        ElMessage({
          message: '请输入邮箱！',
          type: 'error'
        })
        return false
      }

      if ($common.isEmpty(data.code)) {
        ElMessage({
          message: '请输入验证码！',
          type: 'error'
        })
        return
      }

      if (data.username.indexOf(' ') !== -1 || data.password.indexOf(' ') !== -1) {
        ElMessage({
          message: '用户名或密码不能包含空格！',
          type: 'error'
        })
        return
      }

      const user = {
        username: data.username.trim(),
        code: data.code.trim(),
        password: $common.encrypt(data.password.trim())
      }

      if (data.dialogTitle === '邮箱验证码') {
        user.email = data.email
      }

      $http.post($constant.baseURL + '/user/regist', user)
        .then((res) => {
          if (!$common.isEmpty(res.data)) {
            $store.commit('loadCurrentUser', res.data)
            localStorage.setItem('userToken', res.data.accessToken)
            data.username = ''
            data.password = ''
            $router.push({ path: '/' })
            const userToken = $common.encrypt(localStorage.getItem('userToken'))
            window.open($constant.imBaseURL + '?userToken=' + userToken)
          }
        })
        .catch((error) => {
          ElMessage({
            message: error.message,
            type: 'error'
          })
        })
    }

    // 邮箱验证码
    function changeDialog (value) {
      if (value === '邮箱验证码') {
        if ($common.isEmpty(this.email)) {
          ElMessage({
            message: '请输入邮箱！',
            type: 'error'
          })
          return false
        }
        if (!(/^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/.test(data.email))) {
          ElMessage({
            message: '邮箱格式有误！',
            type: 'error'
          })
          return false
        }
      }
      data.dialogTitle = value
      data.showDialog = true
      console.log('对话框打开')
    }

    // 清除前的回调
    function clearDialog () {
      data.password = ''
      data.phoneNumber = ''
      data.email = ''
      data.avatar = ''
      data.showDialog = false
      data.code = ''
      data.dialogTitle = ''
      data.passwordFlag = null
    }

    function checkParams (params) {
      if (data.dialogTitle === '修改手机号' || data.dialogTitle === '绑定手机号' || (data.dialogTitle === '找回密码' && data.passwordFlag === 1)) {
        params.flag = 1
        if ($common.isEmpty(data.phoneNumber)) {
          ElMessage({
            message: '请输入手机号！',
            type: 'error'
          })
          return false
        }
        if (!(/^1[345789]\d{9}$/.test(data.phoneNumber))) {
          ElMessage({
            message: '手机号格式有误！',
            type: 'error'
          })
          return false
        }
        params.place = data.phoneNumber
        return true
      } else if (data.dialogTitle === '修改邮箱' || data.dialogTitle === '绑定邮箱' || data.dialogTitle === '邮箱验证码' || (data.dialogTitle === '找回密码' && data.passwordFlag === 2)) {
        params.flag = 2
        if ($common.isEmpty(data.email)) {
          ElMessage({
            message: '请输入邮箱！',
            type: 'error'
          })
          return false
        }
        if (!(/^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/.test(data.email))) {
          ElMessage({
            message: '邮箱格式有误！',
            type: 'error'
          })
          return false
        }
        params.place = data.email
        return true
      }
      return false
    }

    // 获取验证码
    function getCode () {
      if (data.codeString === '验证码') {
        // 获取验证码
        const params = {}
        if (!checkParams(params)) {
          return
        }
        console.log(params)
        let url
        if (data.dialogTitle === '找回密码' || data.dialogTitle === '邮箱验证码') {
          url = '/user/getCodeForForgetPassword'
        } else {
          url = '/user/getCodeForBind'
        }
        $http.get($constant.baseURL + url, params)
          .then((res) => {
            ElMessage({
              message: '验证码已发送，请注意查收！',
              type: 'success'
            })
          })
          .catch((error) => {
            ElMessage({
              message: error.message,
              type: 'error'
            })
          })
        data.codeString = '30'
        data.intervalCode = setInterval(() => {
          if (data.codeString === '0') {
            clearInterval(data.intervalCode)
            data.codeString = '验证码'
          } else {
            data.codeString = (parseInt(data.codeString) - 1) + ''
          }
        }, 1000)
      } else {
        ElMessage({
          message: '请稍后再试！',
          type: 'warning'
        })
      }
    }

    function updateSecretInfo () {
      if ($common.isEmpty(data.code)) {
        ElMessage({
          message: '请输入验证码！',
          type: 'error'
        })
        return
      }
      if ($common.isEmpty(data.password)) {
        ElMessage({
          message: '请输入密码！',
          type: 'error'
        })
        return
      }
      const params = {
        code: data.code.trim(),
        password: $common.encrypt(data.password.trim())
      }
      if (!checkParams(params)) {
        return
      }

      if (data.dialogTitle === '找回密码') {
        $http.post($constant.baseURL + '/user/updateForForgetPassword', params, false, false)
          .then((res) => {
            clearDialog()
            ElMessage({
              message: '修改成功，请重新登陆！',
              type: 'success'
            })
          })
          .catch((error) => {
            ElMessage({
              message: error.message,
              type: 'error'
            })
          })
      } else {
        $http.post($constant.baseURL + '/user/updateSecretInfo', params, false, false)
          .then((res) => {
            if (!$common.isEmpty(res.data)) {
              $store.commit('loadCurrentUser', res.data)
              data.currentUser = $store.state.currentUser
              clearDialog()
              ElMessage({
                message: '修改成功！',
                type: 'success'
              })
            }
          })
          .catch((error) => {
            ElMessage({
              message: error.message,
              type: 'error'
            })
          })
      }
    }

    // 提交数据
    function submitDialog () {
      if (data.dialogTitle === '修改头像') {
        if ($common.isEmpty(data.avatar)) {
          ElMessage({
            message: '请上传头像！',
            type: 'error'
          })
        } else {
          const user = {
            avatar: data.avatar.trim()
          }

          $http.post($constant.baseURL + '/user/updateUserInfo', user)
            .then((res) => {
              if (!$common.isEmpty(res.data)) {
                $store.commit('loadCurrentUser', res.data)
                data.currentUser = $store.state.currentUser
                clearDialog()
                ElMessage({
                  message: '修改成功！',
                  type: 'success'
                })
              }
            })
            .catch((error) => {
              ElMessage({
                message: error.message,
                type: 'error'
              })
            })
        }
      } else if (data.dialogTitle === '修改手机号' || data.dialogTitle === '绑定手机号' || data.dialogTitle === '修改邮箱' || data.dialogTitle === '绑定邮箱') {
        updateSecretInfo()
      } else if (data.dialogTitle === '找回密码') {
        if (data.passwordFlag !== 1 && data.passwordFlag !== 2) {
          ElMessage({
            message: '请选择找回方式！',
            type: 'error'
          })
        } else {
          updateSecretInfo()
        }
      } else if (data.dialogTitle === '邮箱验证码') {
        data.showDialog = false
      }
    }

    return {
      ...toRefs(data),
      signIn,
      login,
      signUp,
      regist,
      changeDialog,
      clearDialog,
      getCode, // 获取验证码
      submitDialog, // 提交数据
      $constant
    }
  }
}

</script>

<template>
  <div>
    <!-- 登陆和注册 -->
    <!--v-if="$common.isEmpty(currentUser)"    -->
    <div
      class="myCenter in-up-container my-animation-hideToShow">
      <!-- 背景图片 -->
      <el-image class="my-el-image"
                style="position: absolute"
                v-once
                lazy
                :src="$constant.two_poem_image[Math.floor(Math.random() * $constant.two_poem_image.length)]"
                fit="cover">
        <template #error>
          <div class="image-slot"></div>
        </template>
      </el-image>
      <div class="in-up" id="loginAndRegist">
        <div class="form-container sign-up-container">
          <div class="myCenter">
            <h1>注册</h1>
            <input v-model="username" type="text" maxlength="30" placeholder="用户名">
            <input v-model="password" type="password" maxlength="30" placeholder="密码">
            <input v-model="email" type="email" placeholder="邮箱">
            <input v-model="code" type="text" placeholder="验证码" disabled>
            <a style="margin: 0" href="#" @click="changeDialog('邮箱验证码')">获取验证码</a>
            <button @click="regist()">注册</button>
          </div>
        </div>
        <div class="form-container sign-in-container">
          <div class="myCenter">
            <h1>登录</h1>
            <input v-model="account" type="text" placeholder="用户名/邮箱/手机号">
            <input v-model="password" type="password" placeholder="密码">
            <a href="#" @click="changeDialog('找回密码')">忘记密码？</a>
            <button @click="login()">登录</button>
          </div>
        </div>
        <div class="overlay-container">
          <div class="overlay">
            <div class="overlay-panel myCenter overlay-left">
              <h1>已有帐号？</h1>
              <p>请登录🚀</p>
              <button class="ghost" @click="signIn()">登录</button>
            </div>
            <div class="overlay-panel myCenter overlay-right">
              <h1>没有帐号？</h1>
              <p>立即注册吧😃</p>
              <button class="ghost" @click="signUp()">注册</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog :title="dialogTitle"
               v-model="showDialog"
               width="30%"
               :before-close="clearDialog"
               :append-to-body="true"
               :close-on-click-modal="false"
               cente>
        <div class="myCenter" style="flex-direction: column">
            <div>
              <div v-if="dialogTitle === '修改手机号' || dialogTitle === '绑定手机号'">
                <div style="margin-bottom: 5px">手机号：</div>
                <el-input v-model="phoneNumber"></el-input>
                <div style="margin-top: 10px;margin-bottom: 5px">验证码：</div>
                <el-input v-model="code"></el-input>
                <div style="margin-top: 10px;margin-bottom: 5px">密码：</div>
                <el-input v-model="password"></el-input>
              </div>
              <div v-else-if="dialogTitle === '修改邮箱' || dialogTitle === '绑定邮箱'">
                <div style="margin-bottom: 5px">邮箱：</div>
                <el-input v-model="email"></el-input>
                <div style="margin-top: 10px;margin-bottom: 5px">验证码：</div>
                <el-input v-model="code"></el-input>
                <div style="margin-top: 10px;margin-bottom: 5px">密码：</div>
                <el-input v-model="password"></el-input>
              </div>
              <div v-else-if="dialogTitle === '修改头像'">
                <uploadPicture :prefix="'userAvatar'" @addPicture="addPicture" :maxSize="1"
                               :maxNumber="1"></uploadPicture>
              </div>
              <div v-else-if="dialogTitle === '找回密码'">
                <div class="myCenter" style="margin-bottom: 12px">
                  <el-radio-group v-model="passwordFlag">
                    <el-radio :label="1" style="margin-right: 10px">手机号</el-radio>
                    <el-radio :label="2">邮箱</el-radio>
                  </el-radio-group>
                </div>
                <div v-if="passwordFlag === 1">
                  <div style="margin-bottom: 5px">手机号：</div>
                  <el-input v-model="phoneNumber"></el-input>
                  <div style="margin-top: 10px;margin-bottom: 5px">验证码：</div>
                  <el-input v-model="code"></el-input>
                  <div style="margin-top: 10px;margin-bottom: 5px">新密码：</div>
                  <el-input maxlength="30" v-model="password"></el-input>
                </div>
                <div v-else-if="passwordFlag === 2">
                  <div style="margin-bottom: 5px">邮箱：</div>
                  <el-input v-model="email"></el-input>
                  <div style="margin-top: 10px;margin-bottom: 5px">验证码：</div>
                  <el-input v-model="code"></el-input>
                  <div style="margin-top: 10px;margin-bottom: 5px">新密码：</div>
                  <el-input maxlength="30" v-model="password"></el-input>
                </div>
              </div>
              <div v-else-if="dialogTitle === '邮箱验证码'">
                <div>
                  <div style="margin-bottom: 5px">邮箱：</div>
                  <el-input v-model="email"></el-input>
                  <div style="margin-top: 10px;margin-bottom: 5px">验证码：</div>
                  <el-input v-model="code"></el-input>
                </div>
              </div>
            </div>
            <div style="display: flex;margin-top: 30px" v-show="dialogTitle !== '修改头像'">
                        <proButton :info="codeString"
                                   v-show="dialogTitle === '修改手机号' || dialogTitle === '绑定手机号' || dialogTitle === '修改邮箱' || dialogTitle === '绑定邮箱' || dialogTitle === '找回密码' || dialogTitle === '邮箱验证码'"
                                   @click.native="getCode()"
                                   :before="$constant.before_color_1"
                                   :after="$constant.after_color_1"
                                   style="margin-right: 20px">
                        </proButton>
                        <proButton :info="'提交'"
                                   @click.native="submitDialog()"
                                   :before="$constant.before_color_2"
                                   :after="$constant.after_color_2">
                        </proButton>
            </div>
          </div>
    </el-dialog>
  </div>

</template>

<style scoped>

/* 居中 */
.myCenter {
  display: flex;
  justify-content: center;
  align-items: center;
}

.in-up-container {
  height: 100vh;
  position: relative;
}

.in-up {
  opacity: 0.9;
  border-radius: 10px;
  box-shadow: 0 15px 30px var(--miniMask), 0 10px 10px var(--miniMask);
  position: relative;
  overflow: hidden;
  width: 750px;
  max-width: 100%;
  min-height: 450px;
  margin: 10px;
}

.in-up p {
  font-size: 14px;
  letter-spacing: 1px;
  margin: 20px 0 30px 0;
}

.in-up a {
  color: var(--black);
  font-size: 14px;
  text-decoration: none;
  margin: 15px 0;
}

.form-container {
  position: absolute;
  height: 100%;
  transition: all 0.5s ease-in-out;
}

.sign-in-container {
  left: 0;
  width: 50%;
}

.sign-up-container {
  left: 0;
  width: 50%;
  opacity: 0;
}

.form-container div {
  background: var(--white);
  flex-direction: column;
  padding: 0 20px;
  height: 100%;
}

.form-container input {
  background: var(--maxLightGray);
  border-radius: 2px;
  border: none;
  padding: 12px 15px;
  margin: 10px 0;
  width: 100%;
  outline: none;
}

.in-up button {
  border-radius: 2rem;
  border: none;
  background: var(--lightRed);
  color: var(--white);
  font-size: 16px;
  font-weight: bold;
  padding: 12px 45px;
  letter-spacing: 2px;
  cursor: pointer;
}

.in-up button:hover {
  animation: scale 0.8s ease-in-out;
}

.in-up button.ghost {
  background: transparent;
  border: 1px solid var(--white);
}

.sign-up-container button {
  margin-top: 20px;
}

.overlay-container {
  position: absolute;
  left: 50%;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: all 0.5s ease-in-out;
}

.overlay {
  background: var(--gradualRed);
  color: var(--white);
  position: relative;
  left: -100%;
  height: 100%;
  width: 200%;
}

.overlay-panel {
  position: absolute;
  top: 0;
  flex-direction: column;
  height: 100%;
  width: 50%;
  transition: all 0.5s ease-in-out;
}

.overlay-right {
  right: 0;
  transform: translateY(0);
}

.overlay-left {
  transform: translateY(-20%);
}

.in-up.right-panel-active .sign-in-container {
  transform: translateY(100%);
}

.in-up.right-panel-active .overlay-container {
  transform: translateX(-100%);
}

.in-up.right-panel-active .sign-up-container {
  transform: translateX(100%);
  opacity: 1;
}

.in-up.right-panel-active .overlay {
  transform: translateX(50%);
}

.in-up.right-panel-active .overlay-left {
  transform: translateY(0);
}

.in-up.right-panel-active .overlay-right {
  transform: translateY(20%);
}

.user-container {
  width: 100vw;
  height: 100vh;
  position: relative;
}

.user-info {
  width: 80%;
  z-index: 10;
  margin-top: 70px;
  height: calc(100vh - 90px);
  margin-bottom: 20px;
  border-radius: 10px;
  overflow: hidden;
}

.user-left {
  width: 50%;
  background: var(--maxMaxWhiteMask);
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow-y: auto;
  padding: 20px;
}

.user-right {
  width: 50%;
  background: var(--maxWhiteMask);
  padding: 20px;
}

.user-title {
  text-align: right;
  user-select: none;
}

.user-content {
  text-align: left;
}

.user-title div {
  height: 55px;
  line-height: 55px;
  text-align: center;
}

.user-content > div {
  height: 55px;
  display: flex;
  align-items: center;
}

.user-content >>> .el-input__inner, .user-content >>> .el-textarea__inner {
  border: none;
  background: var(--whiteMask);
}

.user-content >>> .el-input__count {
  background: var(--transparent);
  user-select: none;
}

.changeInfo {
  color: var(--white);
  font-size: 0.75rem;
  cursor: pointer;
  background: var(--themeBackground);
  padding: 3px;
  border-radius: 0.2rem;
  user-select: none;
}

@media screen and (max-width: 920px) {
  .user-info {
    width: 90%;
  }

  .user-left {
    width: 100%;
  }

  .user-right {
    display: none;
  }
}
</style>
